$("#loginbtn").click(function () {
    var pwd = $("#password").val();
    var pwdsha = SHA256_hash(pwd);
    var username = $("#username").val();
    var incode = $("#incode").val();
    var search_str = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
    var isEmail = true;
    if (!search_str.test(username)) {
        isEmail = false;
    }
    if (typeof(incode) == "undefined") {
        if (isEmail) {
            $.post("/api/signin", {"username": username, "password": pwd}, function (data) {
                if (data == 'pwdfail') {
                    $("#errtip").html('<div class="alert alert-danger" role="alert"  align="center">密码错误</div>');
                }
                else if (data == 'userfail') {
                    $("#errtip").html('<div class="alert alert-danger" role="alert"  align="center">用户不存在</div>');
                }
                else {
                    $("#maintext").html(data);
                }
            });
        } else {
            $.post("/api/signin", {"username": username, "password": pwdsha}, function (data) {
                if (data == 'pwdfail') {
                    $("#errtip").html('<div class="alert alert-danger" role="alert"  align="center">密码错误</div>');
                }
                else if (data == 'userfail') {
                    $("#errtip").html('<div class="alert alert-danger" role="alert"  align="center">用户不存在</div>');
                }
                else {
                    $("#maintext").html(data);
                }
            });
        }
    } else {
        $.post("/api/register", {"username": username, "password": pwdsha, "incode": incode}, function (data) {
            if (data == 'codefail') {
                $("#errtip").html('<div class="alert alert-danger" role="alert"  align="center">邀请码不存在</div>');
            } else if (data == 'namefail') {
                $("#errtip").html('<div class="alert alert-danger" role="alert"  align="center">用户名已存在</div>');
            } else {
                $("#errtip").html('<div class="alert alert-success" role="alert"  align="center">注册成功，刷新后登录</div>');
            }
        });
    }
});

$("#register").click(function () {
    $("#title").html("Register");
    $("#mainform").append('<input style="opacity:0.8;" name="inputPassword" type="text" id="incode" class="form-control"\n' +
        'placeholder="Invite code" required>');
    $("#loginbtn").attr('id', 'signup');
    $(this).hide();
    $("#signup").html("Sign up");
    $("#errtip").html("");
});
